# coding=UTF-8
'''
Created on 2018年4月3日

@author: lijie
'''
from time import sleep
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains
from utilites.common import Common

class ElementBase():
    f_value=''
    f_name=''
    def __init__(self,v):
        ElementBase.f_value=v
#         self.dr=
        
    def element(self):
        try:
            return Common.driver.find_element_by_xpath(ElementBase.f_value)
        except NoSuchElementException as e:
            Common().logger_error(e)
            return False
        
    def elements(self):
        return Common.driver.find_elements_by_xpath(ElementBase.f_value)
            
    def is_existing(self):
            _element=self.element()
            if _element==False:
                return False     
            if _element.is_displayed():
                return _element
            else:
                return False
            
    def wait_element_present(self,timeout=30):
        '''等待元素出现，默认超时设置30秒
        '''
        i=0
        while i<=timeout:
            if self.is_existing():
                break
            else:
                sleep(1)
                print('was wait for '+str(i)+' seconds')
                i+=1
        if i == timeout:
            Common().logger_error("wait "+self.__class__.__name__+" to present - failed. the element by xpath: "+self.f_value+" was not found in "+str(timeout)+" seconds")
        else:
            Common().logger_info("Execute - wait "+self.__class__.__name__+" to present - success. it shows in "+str(timeout)+" seconds")
            
    def isSelected(self):
        '''判断CheckBox或者radiobutton是否是选中状态
        '''
        el=self.is_existing()
        if el!=False:
            return [el.is_selected(),el]
        else:
            Common().logger_error("Execute - check select status "+self.__class__.__name__+" failed. can't find element by xpath: "+self.f_value)
    
    def select(self):
        '''先判断CheckBox或者radiobutton是否已经选中，如果没有，则调用click方法进行点击选中
            如果已经选中，则不做任何操作，直接抛出已经选中日志
        '''
        el=self.isSelected()
        if not el[0]:
            Common.driver.execute_script("arguments[0].scrollIntoView(false);",el[1])
            el[1].click()
            Common().logger_info("Execute - select "+self.__class__.__name__+" sucess")
        else:
            Common().logger_info("Execute - select "+self.__class__.__name__+" warnning. this element was selected")
        
    def unselect(self):
        '''先判断CheckBox或者radiobutton是否已经选中，如果是选中状态，则调用click方法进行点击取消选中
            如果已经是非选中状态，则不做任何操作，直接抛出已经非选中日志
        '''
        el=self.isSelected()
        if el[0]:
            Common.driver.execute_script("arguments[0].scrollIntoView(false);",el[1])
            el[1].click()
            Common().logger_info("Execute - select "+self.__class__.__name__+" sucess")
        else:
            Common().logger_info("Execute - select "+self.__class__.__name__+" warnning. this element was unselected")
            
    def check_true_and_select(self,flag):
        '''当输入值是true时，则执行勾选操作，适用于CheckBox和radiobutton
        '''
        if str(flag).strip().lower()=='true':
            self.select()
            
    def click(self,how='normal'):
        '''先判断元素是否存在，存在就click
            arg：how  点击方式，默认是normal 普通，如果参数是js，则执行js脚本点击
        '''
        elt=self.is_existing()
        if elt!=False:
            if how=='normal':
                Common.driver.execute_script("arguments[0].scrollIntoView(false);",elt)
                elt.click()
                Common().logger_info("Execute - click "+self.__class__.__name__+" sucess")
            if how=='js':
                try:
                    Common.driver.execute_script("arguments[0].click()",elt)
                    Common().logger_info("Execute - click "+self.__class__.__name__+" via JavaScript - success")
                except Exception as e:
                    Common().logger_error("Execute - click "+self.__class__.__name__+" via JavaScript - failed,get error message "+str(e) )                        
        else:
            Common().logger_error(self.__class_.__name__,"Execute - click "+self.__class_.__name__+" failed. can't find element by xpath: "+self.f_value)
    
    def wait_present_and_click(self,how='normal'):
        '''等待元素出现后，再执行点击
        '''
        self.wait_element_present()
        self.click(how)
        
    def should_exist(self):
        '''对应该存在的元素，判断是否存在
        '''
        elt=self.is_existing()
        if elt!=False:
            Common().logger_info("Assert  - check "+self.__class__.__name__+" should exist - success.")
        else:
            Common().logger_error("Assert  - check "+self.__class__.__name__+" should exist - failed. can't find element by xpath: "+self.f_value)
            
    def should_unexist(self):
        '''对不应该存在的元素，判断是否不存在
        '''
        elt=self.is_existing()
        if elt==False:
            Common().logger_info("Assert  - check "+self.__class__.__name__+" should not exist - success.")
        else:
            Common().logger_error("Assert  - check "+self.__class__.__name__+" should not exist - failed. can't find element by xpath: "+self.f_value)
    
    def input(self,string_text,method='normal'):
        '''对send_keys的二次封装
        arg: method  默认正常模式normal，直接输入，，js，则执行js脚本输入
        '''
        elt=self.is_existing()
        if elt!=False:
            if method=='normal':
                elt.clear()
                elt.send_keys(string_text)   
                Common().logger_info("Execute - input text to "+self.__class__.__name__+" - success. ["+string_text+"] is entered")         
            if method=='js':
                Common.driver.execute_script("return arguments[0].value="+string_text, elt)
                Common.driver.execute_script("$(arguments[0]).change()", elt)
        else:
            Common().logger_error("input text to "+self.__class__.__name__+" - failed. can't find element by xpath: "+self.f_value)
            
    def check_and_input(self,str_text,method='normal'):
        '''判断是否有需要输入的值，有则执行输入
        '''
        if len(str_text)>0:
            self.input(str_text, method)
             
    def get_value(self):
        elt=self.is_existing()
        if elt!=False:
            text=elt.attribute('value')
            Common().logger_info("Execute - get value of "+self.__class__.__name__+" - success. value was:["+text+"]")
            return text
        else:
            Common().logger_error("Execute - get value of "+self.__class__.__name__+" - failed.")
            
    def check_value(self,string):
        '''检查元素的value属性值是否与string相等
        '''
        value=self.get_value()
        if string.strip().lower()==value.strip().lower():
            Common().logger_info("Assert - check "+self.__class__.__name__+" value equal "+string+" - success!!")
        else:
            Common().logger_error("Assert - check "+self.__class__.__name__+" value equal "+string+" - failed. get value was:["+value+"]")
    
    def get_text(self):
        elt=self.is_existing()
        if elt!=False:
            _text=elt.text
            Common().logger_info("Execute - get text of "+self.__class__.__name__+" - success. text was:["+_text+"]")
            return _text
        else:
            Common().logger_error("Execute - get text of "+self.__class__.__name__+" - failed.") 
            
    def check_text(self,string):
        '''检查元素的标签对之间的值是否与string相等
        '''
        text=self.get_text()
        if string.strip().lower()==text.strip().lower():
            Common().logger_info("Assert - check "+self.__class__.__name__+" text equal "+string+" - success!!")
        else:
            Common().logger_error("Assert - check "+self.__class__.__name__+" text equal "+string+" - failed. get text was:["+text+"]")
            
    def get_combox_items(self):
        '''获取下拉框的下拉项
        '''
        el=self.is_existing()
        if el!=False:
            items=[]
            options=Common.driver.find_elements_by_tag_name('option')  
            if len(options)==0:
                options=Common.driver.find_elements_by_tag_name('li')
            if len(options)>0:
                for op in options:
                    items.append(str(op.text))
            else:
                Common().logger_error("no combox items found!!")
            return items
        
    def select_by_item_text(self,item_text):
        '''根据输入的项的值去选择ComboBox和listbox
        '''
        el=self.element()
        if el!=False:
            options=el.find_elements_by_tag_name('li')      # ul生成下拉选项
            if len(options)==0:
                options=el.find_elements_by_tag_name('option')    # 兼容标准select下拉项
            for op in options:               
                if op.text.strip()==item_text.strip():
                    op.click()
                    Common().logger_info("Execute - select item in "+self.__class__.__name__+" by text. - success. select item ["+item_text+"]")
                    break
    
    def check_and_select_by_item_text(self,item_text):
        '''判断是否有需要选择的项，如果有则执行选择
        '''
        if len(item_text)>0:
            self.select_by_item_text(item_text)
            
    def mouse_hover(self):
        '''鼠标悬停方法
        '''
        el=self.element()
        if el!=False: 
            try:
                ActionChains(Common.driver).move_to_element(el).perform()
                Common().logger_info("Execute - Hover mouse on "+self.__class__.__name__+" - success.")
            except Exception as e:
                Common().logger_error(e)
               